import React, { useState, useEffect } from 'react'
import { Table, Button, Modal, notification } from 'antd'
import {
  DeleteOutlined,
  EditOutlined,
  UploadOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import axios from 'axios'

const { confirm } = Modal;

export default function NewsDraft(props) {
  // 初始化数据数组
  const [dataSource, setdataSource] = useState([])
  const {username} = JSON.parse(localStorage.getItem('token'))
  // 获取数据
  useEffect(() => {
    axios.get(`/news?author=${username}&auditState=0&_expand=category`).then(res => {
      console.log(res);
      // setdataSource(res.data)
    })
  }, [username])
  
  // table表格头部定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (id) => <b>{id}</b>,
    },
    {
      title: '新闻标题',
      dataIndex: 'title',
      render: (title, item) => {
        return <a href={`#/news-manage/preview/${item.id}`}>{title}</a>;
      },
    },
    {
      title: '作者',
      dataIndex: 'author',
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      render: (category) => {
        return <span>{category.value}</span>;
      }
    },
    {
      title: '操作',
      key: 'pagepermisson',
      render: (item) => {
        return <div>
          <Button
            type="primary"
            shape="circle"
            style={{ margin: "0px 10px" }}
            icon={<EditOutlined />}
            onClick={() => {
              props.history.push(`/news-manage/update/${item.id}`);
            }}
          />
          <Button
            type="danger"
            shape="circle"
            style={{ margin: "0px 10px" }}
            icon={<DeleteOutlined />}
            onClick={() => confirmMethod(item)}
          />
          <Button
            shape="circle"
            style={{ margin: "0px 10px" }}
            icon={<UploadOutlined />}
            onClick={() => handleCheck(item.id)}
          />
        </div>
      }
    },
  ];

  const handleCheck = (id) => {
    axios.patch(`/news/${id}`, { auditState: 1 }).then((res) => {
      props.history.push("/audit-manage/list");
      notification.info({
        message: "通知",
        description: `您可以到${"审核列表"}中查看您的新闻`,
        placement: "bottomRight",
      });
    });
  };
  
  // 删除事件二次确认
  const confirmMethod = item => {
    confirm({
      title: '您确定要删除吗?',
      icon: <ExclamationCircleOutlined />,
      cancelText: '取消',
      onOk() {
        removeMethed(item)
      },
      onCancel() {},
    });
  }
  // 删除的函数
  const removeMethed = item => {
    // console.log('33', item);
    axios.delete(`/news/${item.id}`).then((res) => {
      setdataSource(dataSource.filter((data) => item.id !== data.id));
    });
  }
  
  return (
    <div>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{
          pageSize: 10
        }}
        rowKey={item=>item.id}
      />
    </div>
  )
}

